package com.seckill.search.service.impl;

import com.seckill.api.client.item.ItemClient;
import com.seckill.api.dto.item.ItemSearchDTO;
import com.seckill.common.utils.BeanUtils;
import com.seckill.search.domain.po.Item;
import com.seckill.search.repository.ItemRepository;
import com.seckill.search.service.IItemService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ItemServiceImpl implements IItemService {

    @Resource
    private ItemRepository itemRepository;
    @Resource
    private ItemClient itemClient;

    @Override
    public void handleItemDelete(Long itemId) {
        // 1.直接删除
        itemRepository.deleteById(itemId);
    }

    @Override
    public void handleItemUp(Long itemId) {
        // 1.根据id查询商品信息
        ItemSearchDTO itemSearchDTO = itemClient.getSearchInfo(itemId);
        if (itemSearchDTO == null) {
            return;
        }
        // 2.数据转换
        Item item = BeanUtils.toBean(itemSearchDTO, Item.class);
        // 3.写入索引库
        itemRepository.save(item);

    }

    @Override
    public void updateItemSold(List<Long> itemIds, int amount) {
        itemRepository.incrementSold(itemIds, amount);
    }

    @Override
    public void handleItemDeletes(List<Long> itemIds) {
        // 1.直接删除
        itemRepository.deleteByIds(itemIds);
    }
}
